
import GreyReactBox from 'grey-react-box'
import { server } from 'server';
import history from 'router/history'

/** 存储 localStorage 的名称 */
const TOKEN = '@Token';

export class UserInfoState {

    /** 用户登陆标识 */
    token?: string | null = window.sessionStorage.getItem(TOKEN);
}

export default class UserInfo extends GreyReactBox<UserInfoState>{

    private static _instance: UserInfo;

    static get instance() {
        return UserInfo._instance || new UserInfo();
    }

    constructor() {
        super(new UserInfoState());
        if (UserInfo._instance) throw new Error('对象为单例'); else UserInfo._instance = this;
    }

    signIn = this.pipeline(async (boxState, opt?: { code: string, redirect: string }) => {
        if(!opt) return;

        // const url = `/medicine/login/getLoginToken`;
        // const ajax = await server.post(url, { code: opt.code }).end();
        // console.log(ajax);

        const url = `/medicine/login/getTestToken`;
        const ajax = await server.get(url, { openId: 'o60JmuG45IzJj7qcILLkRzVMuw8k' }).end();
        if (ajax.err) return;
        
        boxState.token = ajax.res.body.data;
        window.sessionStorage.setItem(TOKEN, ajax.res.body.data)

        history.replace(opt.redirect);
    })
}